package com.rtf.framework.common.dto;

import com.google.common.collect.Maps;
import com.rtf.framework.common.dto.support.DTOCallbackHandler;
import com.rtf.framework.common.util.UtilString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.util.ReflectionUtils;
import org.springframework.format.annotation.NumberFormat;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.Map;

/**
 * 对待转换的实体中的数字进行转换，默认的数字格式为"##.00"
 */
@Slf4j
public class DTOCallbackHandlerWithNumber implements DTOCallbackHandler {

    /**
     * 判断值是否为数字类型
     *
     * @param value
     * @return
     */
    public boolean match(Object value) {
        return value != null && value instanceof Number;
    }

    /**
     * 进行日期格式转换的处理
     *
     * @param dtoMap
     */
    @Override
    public void doHandler(Map<String, Object> dtoMap, Class<?> itemClass) {
        //判断map是否为空
        if (dtoMap == null) {
            return;
        }
        Map<String, Object> dateMap = Maps.newHashMap();
        dtoMap.entrySet().stream().filter(item -> UtilString.isNotBlank(item.getKey()) && match(item.getValue()))
                .forEach(item -> {
                    try {
                        NumberFormat numberFormat = null;
                        if (!Map.class.isAssignableFrom(itemClass)) {
                            try {
                                Field dateField = ReflectionUtils.findRequiredField(itemClass, item.getKey());
                                numberFormat = dateField.getAnnotation(NumberFormat.class);
                            } catch (Exception e) {
                            }
                        }
                        if (numberFormat != null) {
                            dateMap.put(item.getKey(), new DecimalFormat(numberFormat.pattern()).format(item.getValue()));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
        dtoMap.putAll(dateMap);
    }
}
